<script setup>
import { Search } from '@element-plus/icons-vue'
import { GetListDetailAPI } from '@/api/material/common'
import { GetBomAPI } from '@/api/material/common'
import Production from './production.vue'
import { getStockInfoBomAPI } from '@/api/warehouse/outbound/producfield.js'

import Bom from './bom.vue'
import { computed, nextTick } from 'vue'
const { proxy } = getCurrentInstance()

// 封装 方法 字典查询
const {
  subcontracting_order_type // 委外类型
} = proxy.useDict('subcontracting_order_type')

const props = defineProps({
  data: {
    type: Object,
    default: {}
  },
  // 是否禁用
  db: {
    type: Boolean,
    default: false
  }
})

// 物料弹窗
const materialShow = ref(false)
const materialShow2 = ref(false)
const supplierIsShow = ref(false)
// bom弹窗
const bomShow = ref(false)

// 生产计划弹窗
const productionOrderIsShow = ref(false)

// 表单Ref
const ruleFormRef = ref(null)

// 是否禁用物料
const materialDis = ref(false)

// 勾选的数据
const handleSelect = ref([])

// 表单字段
const ruleForm = reactive({
  subcontractingType: '2',
  materialType: '', // 物料类型
  materialTypeDict: '', // 物料类型
  associatedDocNum: '', // 关联单号
  bomCode: '', // BOM编码
  bomName: '', // BOM名称
  subcontractingWeight: '', // 委外数量
  demandTime: '', // 需求时间
  materialId: '', // 物料id
  materialCode: '', // 物料编码
  materialDetailList: [] //  warehouseWeight 出库数量
})

// 回显
watchEffect(() => {
  for (let Key in props.data) {
    ruleForm[Key] = props.data[Key]
  }
})

// 校验
const rules = reactive({
  subcontractingType: [{ required: true, message: '请选择BOM编码', trigger: 'change' }],
  // associatedDocNum: [{ required: true, message: '请输入关联单号', trigger: 'blur' }],
  bomCode: [{ required: true, message: '请选择BOM编码', trigger: 'change' }],
  demandTime: [{ required: true, message: '请选择需求时间', trigger: 'change' }],
  supplierName: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
  machiningPrice: [{ required: true, message: '请输入加工单价', trigger: 'blur' }],
  subcontractingWeight: [{ required: true, message: '请填写委外数量', trigger: 'change' }]
})
// 移除单个校验
const clearValidate = associatedDocNum => {
  ruleFormRef.value.clearValidate(associatedDocNum)
}

// 委外类型选择
const typeChange = (val = 1) => {
  // console.log(val, 'val')
  rules.associatedDocNum = [{ required: true, message: '请输入关联单号', trigger: 'blur' }]
  if (val == 1) {
    materialDis.value = true
  } else if (val == 2) {
    materialDis.value = false
    delete rules.associatedDocNum
  }
  ruleForm.materialType = ''
  ruleForm.materialId = ''
  ruleForm.materialCode = ''
  ruleForm.materialName = ''
  ruleForm.materialSpec = ''
  ruleForm.materialTypeDict = ''
  ruleForm.bomCode = ''
  ruleForm.associatedDocNum = ''
  setTimeout(() => {
    ruleFormRef.value.clearValidate()
  })
}
typeChange()

// 物料选择
const materialSelsct = val => {
  ruleForm.materialId = val.materialId
  ruleForm.materialCode = val.materialCode
  ruleForm.materialName = val.materialName
  ruleForm.specType = val.specType
  ruleForm.materialTypeDict = val.materialTypeDict
  materialShow.value = false
  getList()
}

/**
 * 物料信息弹窗
 */
const addTable = () => {
  materialShow2.value = true
}

/**
 * 物料信息确认
 */
const materialSub2 = obj => {
  const arr = obj.list.map(item => item)
  arr.forEach(items => {
    ruleForm.materialDetailList.push(items)
  })
  materialShow2.value = false
}

// 生产计划单
const productionSub = obj => {
  ruleForm.associatedDocNum = obj.planCode
  ruleForm.materialId = obj.planMaterialId
  ruleForm.materialCode = obj.planMaterialCode
  ruleForm.materialName = obj.planMaterialName
  ruleForm.materialSpec = obj.planMaterialSpec
  ruleForm.materialTypeDict = obj.planMaterialTypeDict
  ruleForm.thickness = obj.thickness
  productionOrderIsShow.value = false
  getList()
}

// BOM选择
const bomSelsct = val => {
  if (!val) return
  const result = bomSelList.value.find(t => t.bomCode == val)
  if (!result) return
  ruleForm.bomId = result.bomId
  ruleForm.bomNumber = ruleForm.bomCode
  ruleForm.materialTypeDict = result.bomType == 3 ? '半成品' : '成品'
  ruleForm.materialType = result.bomType
  ruleForm.materialDetailList.forEach(item => (item.bomProportion = result.bomProportion))
  bomShow.value = false

  // 查询bom详情(材料BOM)
  getBomList(ruleForm.bomId)
}

/**
 * 委外数量回车
 */
const subcontractingWeightkeyup = async () => {
  ruleForm.materialDetailList = []
  try {
    if (!ruleForm.materialCode) return proxy.warningMsg('请先选择物料编码!')
    const res = await getStockInfoBomAPI({
      materialCode: ruleForm.materialCode,
      planWeight: ruleForm.subcontractingWeight
    })
    // res.data.forEach(item => {
    //   ruleForm.list.push(item)
    // })
    ruleForm.materialDetailList = res.data
  } catch (error) {}
}

// 材料bom
const getBomList = async bomId => {
  try {
    const res = await GetListDetailAPI({ pageNum: 1, pageSize: 999, bomId })
    ruleForm.materialDetailList = res.data
    //   计算每个需求量
    ruleForm.materialDetailList.forEach(item => (item.需求量 = item.inventory * item.bomDetailDosage))
  } catch {
  } finally {
  }
}

const bomSelList = ref([])

// 查询 Bom
const getList = async () => {
  try {
    const res = await GetBomAPI({
      pageNum: 1,
      pageSize: 9999,
      materialCode: ruleForm.materialCode
    })
    bomSelList.value = res.rows
  } catch {
  } finally {
  }
}

// 勾选数据
const handleSelectionChange = row => {
  handleSelect.value = row
}

// 删除表格表单
const remove = () => {
  if (handleSelect.value.length > 0) {
    handleSelect.value.forEach(item => {
      const Find = ruleForm.materialDetailList.findIndex(itemy => item.id == itemy.id)
      ruleForm.materialDetailList.splice(Find, 1)
    })
  } else {
    ruleForm.materialDetailList.splice(ruleForm.materialDetailList.length - 1, 1)
  }
}

/**
 * 类型
 */
const isTypeList = async () => {
  ruleForm.materialDetailList = []
  try {
    const res = await getStockInfoBomAPI({
      materialCode: ruleForm.materialCode,
      planWeight: ruleForm.subcontractingWeight,
      isTwoFlag: true
    })
    ruleForm.materialDetailList = res.data
  } catch (error) {}
}

// 供应商选择
const supplierSub = val => {
  ruleForm.supplierName = val.supplierName
  ruleForm.supplierId = val.id
  supplierIsShow.value = false
}

// 提交
const submit = async () => {
  return new Promise((resolve, reject) => {
    ruleFormRef.value.validate(async (valid, fields) => {
      if (!valid) {
        proxy.warningMsg('请填写完整')
        resolve(false)
        return
      }

      // const isif = ruleForm.materialDetailList.every(item => item.warehouseWeight > 1 && item.warehouseWeight)
      // if (!isif) {
      //   resolve(false)
      //   proxy.warningMsg('出库量为必填,且不能小于1!')
      //   return
      // }

      const re = ruleForm.materialDetailList.some(t => t.warehouseWeight > t.stockWeight)
      if (re) {
        const MesBox = await proxy.DelMessageBox('当前需求量大于库存量，是否继续？')
        if (!MesBox) return
        resolve(ruleForm)
      } else {
        resolve(ruleForm)
      }
    })
  })
}
defineExpose({ submit })

// const dis = computed(() => {
//   if (ruleForm.subcontractingType == 1) {
//     return !ruleForm.associatedDocNum ? true : false
//   } else {
//     return !ruleForm.materialCode ? true : false
//   }
// })
</script>
<template>
  <div class="app-container">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" inline label-width="80px" :size="formSize" status-icon>
      <el-form-item label="委外类型" prop="subcontractingType">
        <el-select v-model="ruleForm.subcontractingType" placeholder="请选择委外类型">
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in subcontracting_order_type"
            :key="index"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="关联单号" prop="associatedDocNum">
        <el-input
          clearable
          v-model="ruleForm.associatedDocNum"
          :disabled="!materialDis || props.db"
          :suffix-icon="Search"
          @click="productionOrderIsShow = true"
        />
      </el-form-item> -->
      <!--  :disabled="!ruleForm.materialType" -->

      <el-form-item label="物料编码" prop="materialCode">
        <el-input clearable :suffix-icon="Search" v-model="ruleForm.materialCode" @click="materialShow = true" />
      </el-form-item>
      <el-form-item label="BOM" prop="bomCode" v-if="ruleForm.subcontractingType != '3'">
        <!-- @change="bomSelsct" -->
        <el-select v-model="ruleForm.bomCode" filterable reserve-keyword>
          <el-option v-for="item in bomSelList" :key="item.bomCode" :label="item.bomCode" :value="item.bomCode" />
        </el-select>
        <!-- 
        <el-input
          multiple
          reserve-keyword
          :disabled="dis"
          clearable
          :suffix-icon="Search"
          v-model="ruleForm.bomCode"
          @click="bomShow = true"
        /> -->
      </el-form-item>

      <el-form-item label="物料名称" prop="materialName">
        <el-input clearable v-model="ruleForm.materialName" disabled />
      </el-form-item>
      <el-form-item label="规格型号">
        <el-input clearable v-model="ruleForm.specType" disabled />
      </el-form-item>
      <el-form-item label="点数">
        <el-input clearable v-model="ruleForm.pointPosition" />
      </el-form-item>
      <el-form-item label="物料类别" prop="materialTypeDict">
        <el-input clearable v-model="ruleForm.materialTypeDict" disabled />
      </el-form-item>
      <el-form-item label="委外数量" prop="subcontractingWeight">
        <el-input
          clearable
          @change="proxy.check(ruleForm.subcontractingWeight)"
          type="number"
          @keyup.enter="subcontractingWeightkeyup"
          oninput="if(value<=0)value=''"
          v-model="ruleForm.subcontractingWeight"
          :disabled="props.db"
        />
      </el-form-item>
      <el-form-item label="需求时间" prop="demandTime">
        <el-date-picker
          v-model="ruleForm.demandTime"
          type="datetime"
          placeholder="请选择需求时间"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled="props.db"
        />
      </el-form-item>
      <el-form-item label="加工单价" prop="machiningPrice">
        <el-input type="number" :min="0" clearable v-model="ruleForm.machiningPrice" :disabled="props.db" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <el-input clearable v-model="ruleForm.supplierName" @click="supplierIsShow = true" :disabled="props.db" />
      </el-form-item>
      <div class="flex-items-center">
        <label class="remarkLabel">备注</label>
        <el-input
          autosize
          clearable
          v-model="ruleForm.remark"
          :rows="2"
          type="textarea"
          placeholder="请输入内容"
          :input-style="{ width: '95%' }"
        />
      </div>
    </el-form>
    <p-table-add title="物料信息" @add="addTable" @remove="remove" />
    <el-button type="warning" @click="isTypeList">类型</el-button>
    <el-table
      v-loading="loading"
      stripe
      border
      :data="ruleForm.materialDetailList"
      style="margin-top: 10px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" width="70" type="index" />
      <!-- <el-table-column label="类别" prop="materialTypeDict" width="150" /> -->
      <el-table-column label="物料名称" prop="materialName" width="auto" />
      <el-table-column label="物料编码" prop="materialCode" width="auto" />
      <el-table-column label="规格型号" prop="specType" width="auto" />
      <!-- <el-table-column label="物料类别" prop="materialCategoryDict" width="150" /> -->
      <!-- <el-table-column label="占比" prop="bomProportion" width="120"> -->
      <!-- <template #default="scope">
          <span>{{ ruleForm.subcontractingWeight }}</span>
        </template> -->
      <!-- </el-table-column> -->
      <el-table-column label="库存量 " prop="stockNum" width="auto" />
      <el-table-column label="单位" prop="materialUnitDict" width="auto" />
      <!-- <el-table-column label="计算量" prop="需求量" width="120">
        <template #default="{ row }">
          {{ ((ruleForm.subcontractingWeight * (row.bomProportion || 1)) / 100).toFixed(2) }}
        </template>
      </el-table-column> -->

      <el-table-column label="需求量" align="center" width="120">
        <template #default="{ row }">
          <div class="inputClass">
            <el-input type="number" oninput="if(value<=0)value=''" clearable v-model="row.plannedWeight" />
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 物料弹窗 -->
    <Material
      :is-show="materialShow"
      :dict="[
        { label: '原料', value: '1' },
        { label: '半成品', value: '3' },
        { label: '成品', value: '4' }
      ]"
      @preservation="materialSelsct"
      @cancel="materialShow = false"
    />
    <Supplier :is-show="supplierIsShow" @preservation="supplierSub" @cancel="supplierIsShow = false" />
    <Material
      :is-show="materialShow2"
      :dict="[
        {
          label: '原料',
          value: '1'
        },
        {
          label: '半成品',
          value: '3'
        },
        {
          label: '辅料',
          value: '2'
        },
        {
          label: '成品',
          value: '4'
        }
      ]"
      :bdb="false"
      @preservation="materialSub2"
      @cancel="materialShow2 = false"
    />

    <!-- 生产计划 -->
    <!-- <Production
      :is-show="productionOrderIsShow"
      @preservation="productionSub"
      @cancel="productionOrderIsShow = false"
    /> -->
    <!-- BOM -->
    <!-- <p-XiaoheDialog :dialogVisible="bomShow" title="BOM选择" @close="bomShow = false" width="50%">
      <template #body>
        <Bom :materialCode="ruleForm.materialCode" @preservation="bomSelsct" @cancel="bomShow = false"
      /></template>
    </p-XiaoheDialog> -->
  </div>
</template>

<style scoped>
.app-container {
  width: 100%;
}

.app-container /deep/ .el-input__inner {
  width: 220px !important;
}
.inputClass /deep/ .el-input__inner {
  width: 100px !important;
}
</style>
